package com.sm.filemanagelibrary;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scorpio.baselibrary.ui.BasicTitleActivity;
import com.scorpio.baselibrary.utils.FileUtil;
import com.scorpio.baselibrary.utils.OpenFileUtils;
import com.sm.filemanagelibrary.adapter.FileManageAdapter;
import com.sm.filemanagelibrary.adapter.FileRootPathAdapter;
import com.sm.filemanagelibrary.model.FileCacheEntity;
import com.sm.filemanagelibrary.model.FileEntity;
import com.sm.filemanagelibrary.model.FolderEntity;
import com.sm.filemanagelibrary.util.FileLoadingUtil;
import com.sm.filemanagelibrary.util.OnFileLoadingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileSdCardActivity extends BasicTitleActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener {

    private SwipeRefreshLayout refreshLayout;
    private List<FileEntity> entityList = new ArrayList<>();
    private List<FileCacheEntity> cachePath = new ArrayList<>();
    private FileManageAdapter adapter;
    private FileRootPathAdapter pathAdapter;
    private RecyclerView recyclerView;
    private RecyclerView rootPathRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private RecyclerView.LayoutManager mrootPathLayoutManager;

    @Override
    protected int onCreateLayout() {
        return R.layout.activity_sd_card;
    }

    @Override
    protected void onInit(Bundle savedInstanceState) {
        setBasicTitle(R.string.file_string_00001);
        showBackBtn();
        refreshLayout = v.getView(R.id.swipeRefreshLayout);
        recyclerView = v.getView(R.id.recyclerView);
        rootPathRecyclerView = v.getView(R.id.recyclerView);
        refreshLayout.setOnRefreshListener(this);
        v.setRecyclerViewAdapter(R.id.recyclerView, adapter = new FileManageAdapter(entityList))
                .setRecyclerViewLayoutManager(R.id.recyclerView, mLayoutManager = new LinearLayoutManager(this));

        v.setRecyclerViewAdapter(R.id.rootPathRecyclerView, pathAdapter = new FileRootPathAdapter(cachePath))
                .setRecyclerViewLayoutManager(R.id.rootPathRecyclerView
                        , mrootPathLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        adapter.setOnItemChildClickListener(this);
        pathAdapter.setOnItemChildClickListener(this);
        loadingFile();
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof FileManageAdapter) {
            if (view.getId() == R.id.file_manage_item_layout) {
                FileEntity entity = (FileEntity) adapter.getData().get(position);
                if (entity.isDirectory) {
                    FileCacheEntity cacheEntity = getFrontCache();
                    View topView = mLayoutManager.getChildAt(0);          //获取可视的第一个view
                    cacheEntity.lastOffset = topView.getTop();                    //获取与该view的顶部的偏移量
                    cacheEntity.lastPosition = mLayoutManager.getPosition(topView);  //得到该View的数组位置
                    inNewPath(entity.path);
                }else {
                    OpenFileUtils.openFiles(entity.path,this);
                }
            }
        } else if (adapter instanceof FileRootPathAdapter) {
            synchronized (cachePath) {
                if (cachePath.size() - 1 == position) return;
                List<FileCacheEntity> cpath = new ArrayList<>();
                for (int i = 0; i <= position; i++) {
                    cpath.add(cachePath.get(i));
                }
                cachePath.clear();
                cachePath.addAll(cpath);
                pathAdapter.notifyDataSetChanged();
                mrootPathLayoutManager.scrollToPosition(pathAdapter.getData().size() - 1);
                loadingFile();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            synchronized (entityList) {
                if (cachePath.size() > 1) {
                    cachePath.remove(cachePath.size() - 1);
                    loadingFile();
                    pathAdapter.notifyDataSetChanged();
                    mrootPathLayoutManager.scrollToPosition(pathAdapter.getData().size() - 1);
                    return false;
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取当前加载最新的文件夹路径缓存
     *
     * @return
     */
    private FileCacheEntity getFrontCache() {
        synchronized (cachePath) {
            if (cachePath.size() == 0) {
                cachePath.clear();
                cachePath.add(new FileCacheEntity(FileUtil.getSDPath()));
                pathAdapter.notifyDataSetChanged();
                mrootPathLayoutManager.scrollToPosition(pathAdapter.getData().size() - 1);
            }
            FileCacheEntity cacheEntity = cachePath.get(cachePath.size() - 1);
            return cacheEntity;
        }
    }

    /**
     * 进入新的路径
     *
     * @param path
     */
    private void inNewPath(String path) {
        synchronized (cachePath) {
            cachePath.add(new FileCacheEntity(path));
            pathAdapter.notifyDataSetChanged();
            mrootPathLayoutManager.scrollToPosition(pathAdapter.getData().size() - 1);
            loadingFile();
        }
    }

    /**
     * 加载文件
     */
    private void loadingFile() {
        refreshLayout.setRefreshing(true);
        final FileCacheEntity cacheEntity = getFrontCache();
        FileLoadingUtil.loadingPathFile(cacheEntity.path, new OnFileLoadingListener() {
            @Override
            public void onfileLoading(List<FolderEntity> foldersEntity) {
                synchronized (entityList) {
                    entityList.clear();
                    entityList.addAll(foldersEntity.get(0).getSubItems());
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    ((LinearLayoutManager) mLayoutManager).scrollToPositionWithOffset(cacheEntity.lastPosition, cacheEntity.lastOffset);
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        loadingFile();
    }

}
